/*
Name:		Sakshi Saini
Roll no.:	2010072
Hash function:	Linear probing (Division Method)
*/
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
struct account
	{
	char usrid[20];
	char passwd[20];
	}*acc;

void get_data(void);
int get_index(int,int);
void make_hash(void);
int hash_func(char*);
void check_hash(void);

char usrt[20],passt[20];

void main()
{
	acc = malloc(97*(sizeof(struct account)));		//size of hash table can be changed acc. to desired 'alpha'
	int c,i=0,j=0;
	
	FILE *fp;
	
	char line[100];
	fp=fopen("data.txt","r");
	
	while(fgets(line, 200,fp))
		{
		sscanf(line,"%s\t%s\n",usrt,passt);		
		make_hash();					//stores text file details in hash table 1 by 1
		}
	fclose(fp);
	
	check_hash();
}

void get_data(void)						//get userid & password from user
{
	printf("\n Enter your user ID :");
	gets(usrt);
	printf("\n Enter your password :");
	gets(passt);
}

int get_index(int key, int offset )				//calculates the key(index) using hash function 
{
	int index = ((key%97)+offset)%97;
 	return index;
 
 }


int hash_func(char* str)					//decides the hash function used in this program
{
	int sum =0,i=0;
	while(str[i] !='\0')
	{
		sum=sum+(str[i]*i);
		i++;
	}
return sum;
}

void make_hash()						//storing values using linear probing
{
	int i,sum=0;
	sum = hash_func(usrt);		 
	for(i=0;i<97;i++)
		{		
		int index = get_index(sum,i);	
		if (acc[index].usrid[0]=='\0')
			{		
		         strcpy(acc[index].usrid,usrt);		
			 strcpy(acc[index].passwd,passt);
          printf("%d    %d    %s\n",index,i,usrt);
			break;
			}
		}		
}


void check_hash()						//checks if the login details are valid or not
{
	int i=0,sum=0,match=0,m=0;
     	sum = hash_func(usrt);
     	for(m=0;m<3;m++)
     		{
     		get_data();
     		for(i=0;i<97;i++)
			{	
			int index = get_index(sum,i);		  	 	
			if(!strcmp(acc[index].usrid,usrt) && !strcmp(acc[index].passwd,passt))
				{
				match = 1;
				break;
				}  
			}if(match==1) break;
			printf("Invalid login.Enter correct data.\n");
		}
	if (match)
	printf("User ID & password accepted\n");
	else
	printf("User ID & password not accepted\n");			
}